package org.libl.dao.admin.impl;

import org.libl.utils.JDBCPoolUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.libl.dao.admin.*;
import org.libl.domain.Admin;

/**
 * 管理员模块:持久层实现类
 */
public class AdminDaoImpl implements AdminDao {
    //1.创建模板类对象
    private JdbcTemplate jt = new JdbcTemplate(JDBCPoolUtils.getDs());
    public Admin findByNameAndPassword(String nameForm, String pswForm){
        try {
            //查询成功:
            //1.编写sql语句
            String sql = "select * from tab_admin where username=? and password=?";
            //2.执行查询方法
            Admin admin = jt.queryForObject(sql,
                    new BeanPropertyRowMapper<Admin>(Admin.class),
                    nameForm,
                    pswForm);
            return admin;
        } catch (DataAccessException e) {
            //查询失败
           return null;
        }
    }

    public int addAdmin(Admin adminForm){
        //1.编写sql
        String sql = "insert into tab_admin values(?,?,?)";
        //2.调用更新方法
        int row = jt.update(sql,
                adminForm.getId(),
                adminForm.getUsername(),
                adminForm.getPassword());
        return row;
    }

    public Admin findAdminByCount(String count){
        try {
            //查询成功:
            //1.编写sql语句
            String sql = "select * from tab_admin where username=?";
            //2.执行查询方法
            Admin admin = jt.queryForObject(sql,
                    new BeanPropertyRowMapper<Admin>(Admin.class),
                    count);
            return admin;
        } catch (DataAccessException e) {
            e.printStackTrace();
            //查询失败
            return null;
        }
    }

    public int edit(String username,String password){

        //1.编写sql
        String sql = "update tab_admin set password=? where username = ?";
        //2.调用更新方法
        int row = jt.update(sql,password,username);
        return row;
    }
}
